<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇我们将基础全面整体的对 ECMAScript 中 Array 类型进行学习。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：Array">
<meta property="og:url" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇我们将基础全面整体的对 ECMAScript 中 Array 类型进行学习。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/javascript.jpg">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/stack.png">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/queue.png">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/reserve_queue.png">
<meta property="og:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/insert-sort.gif">
<meta property="og:updated_time" content="2019-04-22T15:13:14.691Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：Array">
<meta name="twitter:description" content="本篇我们将基础全面整体的对 ECMAScript 中 Array 类型进行学习。">
<meta name="twitter:image" content="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/">





  <title>《JavaScript 高级程序设计》第五章：Array | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/01/professional-javascript-chapter-5-Array/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：Array</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-01T07:19:58+08:00">
                2019-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/04/01/professional-javascript-chapter-5-Array/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇我们将基础全面整体的对 ECMAScript 中 <code>Array</code> 类型进行学习。</blockquote>

<a id="more"></a>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>组成数组的每一项可以称之为 “数组元素”，也可以称之为 “数据项”，并且每个数组元素都有一个与之对应的下标（索引）。<br>ECMAScript 中创建数组主要有两种方式：</p>
<p><strong>构造函数</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> <span class="built_in">Array</span>(); <span class="comment">//创建一个默认的空数组</span></span><br><span class="line"><span class="keyword">var</span> arr2 = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>); <span class="comment">//创建一个空数组，但初始化好数组的长度</span></span><br><span class="line"><span class="keyword">var</span> arr3 = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="string">'a'</span>); <span class="comment">//创建一个数组，并依次按顺序保存传入的数组元素的值。</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>在这个例子中 <code>arr</code> 、<code>arr2</code> 、 <code>arr3</code> 都是构造函数 <code>Array()</code> 的实例数组对象。</p>
</blockquote>
<p><strong>字面量</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>];</span><br></pre></td></tr></table></figure>
<blockquote>
<p>需要注意的是，如果数组中存在以逗号隔开的空值，那么数组元素的数量，在不同的浏览器将存在兼容性问题。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, ];</span><br><span class="line"></span><br><span class="line"><span class="comment">/* IE 8.0 - */</span></span><br><span class="line"></span><br><span class="line">arr.length <span class="comment">// 3;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* IE 9.0 + / Chrome / Firefox */</span></span><br><span class="line"></span><br><span class="line">arr.length <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>在 <code>IE8.0-</code> 下只要有逗号分隔就存在着数组元素，默认为 <code>undefined</code> 。 </p>
</blockquote>
<h2 id="legnth"><a href="#legnth" class="headerlink" title="legnth"></a>legnth</h2><p>Array 的长度是动态的，通过 <code>length</code> 属性可以实时获取数组的当前长度，但 <code>length</code> 属性却并非是只读的，通过 <code>length</code> 属性我们可以手动调整数组的长度，删除数组尾部的元素，也或者向数组的尾部新增数组元素。</p>
<ul>
<li>获取数组长度</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="string">'a'</span>, <span class="literal">true</span>];</span><br><span class="line"></span><br><span class="line">arr.length; <span class="comment">//3</span></span><br></pre></td></tr></table></figure>
<ul>
<li>删除数组最后一个元素</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr.length = <span class="number">2</span>;</span><br><span class="line">arr[<span class="number">2</span>]; <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<ul>
<li>新增數組元素（在尾部）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr.length = <span class="number">3</span>;<span class="comment">//(3) [1, "a", empty]</span></span><br><span class="line">arr[arr.length] = <span class="literal">false</span>; <span class="comment">//(4) [1, "a", empty, false]</span></span><br></pre></td></tr></table></figure>
<h2 id="检测数组"><a href="#检测数组" class="headerlink" title="检测数组"></a>检测数组</h2><p><code>isArray()</code> 是 ES5 为 Array 类型最新添加的静态方法，它可以有效的解决不是一个全局环境中的“引用类型”是否为数组的判断。<br>例如：从 A 框架(iframe)中传入到 B 框架的数组就不是一个全局环境，对于这种情况，单纯的 <code>instanceof</code> 操作符将会失效。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.isArray(arr);</span><br></pre></td></tr></table></figure>
<p>返回值是一个 <code>Boolean</code>类型，兼容性：IE9+。</p>
<p>如果考虑兼容性并且笃定当前的引用类型不会跨全局环境，则可以直接使用 <code>instanceof</code> 操作符。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">arr <span class="keyword">instanceof</span> <span class="built_in">Array</span>; <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>也或者通过引用类型的 <code>constructor</code> 属性来判断：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">arr.constructor == <span class="built_in">Array</span> <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>更或者可以基于行为来判断：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isArray</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> target != <span class="string">'object'</span>) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">return</span> target.length &gt;= <span class="number">0</span> &amp;&amp; target.pop &amp;&amp; target.push;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后，还可以通过 <code>Object.toString()</code> 方法返回的固定格式结果来进行类型的匹配。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isType</span>(<span class="params">target, type</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Object</span>.prototype.toString.call(target) === <span class="string">'[object '</span> + type + <span class="string">']'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">isType([],<span class="string">'Array'</span>);</span><br></pre></td></tr></table></figure>
<p>多种方法相比较，第一种最适用，但存在兼容性问题，而第二种无法解决跨全局的问题，最后的两种无疑更加通用。</p>
<h2 id="转换方法"><a href="#转换方法" class="headerlink" title="转换方法"></a>转换方法</h2><p>在 JavaScript 中一切皆对象，其中 <code>Object</code> 是一切其它对象的基础对象，所有其它对象都继承于 <code>Object</code>，所以同理，Array 也具有 <code>toString()</code>、<code>toLocaleString()</code>、<code>valueOf()</code> 这三个方法，只是 Array 中这三个方法并不是单纯的继承于 Object，而是对这三个方法进行了一定特殊的重写，差异则体现在 Array 中这三个方法返回值并不与 Object 的相同，而是更契合自身的结果。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a1 = [];</span><br><span class="line"><span class="keyword">var</span> a2 = [<span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"blue"</span>];</span><br><span class="line"><span class="keyword">var</span> a3 = [&#123;&#125;, &#123;&#125;];</span><br></pre></td></tr></table></figure>
<p><strong>toString()</strong></p>
<p><code>toString()</code> 与 <code>toLocaleString()</code> 方法会将数组元素转换为字符串，并以“逗号”作为默认的分隔符进行拼接返回。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a1.toString(); <span class="comment">//"";</span></span><br><span class="line">a2.toString(); <span class="comment">//"red,green,blue"</span></span><br></pre></td></tr></table></figure>
<p>当数组元素是基本数据类型时，这一转换会很直观，但是当数组元素的值是一个“引用类型”时，结果将会有些不同。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a3.toString(); <span class="comment">//"[object Object],[object Object]"</span></span><br></pre></td></tr></table></figure>
<p>这是因为 Array 的 <code>toString()</code> 方法遇到“引用类型”的值时会继续调用这个“引用类型”的 <code>toString()</code> 方法或 <code>toLocaleString()</code>，直到返回的结果是一个基本类型为止。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> f = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> r = <span class="keyword">new</span> <span class="built_in">RegExp</span>();</span><br><span class="line"><span class="keyword">var</span> b = <span class="keyword">new</span> <span class="built_in">Boolean</span>(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">[f, r, b].toString(); <span class="comment">// "function()&#123;&#125;,/(?:)/,false"</span></span><br></pre></td></tr></table></figure>
<p>更严谨的说当 Array 的 <code>toString()</code> 方法遇到的是一个“引用类型”的值时会先调用这个引用对象的 <code>valueOf()</code> 方法，当 <code>valueOf()</code> 方法的返回值依然是一个引用类型时，才会调用这个对象的 <code>toString()</code> 方法，直到返回的值是一个基本数据类型为止。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [&#123;</span><br><span class="line">    valueOf: <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="keyword">return</span> <span class="number">1</span> &#125;,</span><br><span class="line">    toString: <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="keyword">return</span> <span class="string">'A'</span> &#125;</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    valueOf: <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="keyword">return</span> &#123; <span class="attr">toString</span>: <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="keyword">return</span> <span class="number">2</span> &#125; &#125; &#125;,</span><br><span class="line">    toString: <span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="keyword">return</span> <span class="string">'B'</span> &#125;</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">arr.toString(); <span class="comment">// "A,B"</span></span><br></pre></td></tr></table></figure>
<p><strong>valueOf()</strong><br>返回数组实例对象本身。</p>
<p><strong>join()</strong></p>
<p>数组除了以上所有引用类型都具有的三个基本转换方法，还有一个私有的转换方法 — <code>join()</code>。</p>
<p><code>join()</code> 与 <code>toString()</code> 功能非常相似，区别只是 <code>toString()</code> 只能默认以“逗号”作为分隔符来拼接每个转换为字符串的数组元素，而 <code>join()</code> 方法则可以自定义要拼接的分隔符。当然如果不指定特定的分隔符，<code>join()</code> 方法默认的也是以“逗号”作为分隔符。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>];</span><br><span class="line">arr.join(); <span class="comment">// "red,green,blue"</span></span><br><span class="line">arr.join(<span class="string">'|'</span>); <span class="comment">// "red|green|blue"</span></span><br><span class="line">arr.join(<span class="string">'||'</span>); <span class="comment">// "red||green||blue"</span></span><br></pre></td></tr></table></figure>
<h2 id="栈方法"><a href="#栈方法" class="headerlink" title="栈方法"></a>栈方法</h2><p>利用 Array 自带的一些方法，我们可以很轻易的模拟其它的数据结构，例如：“栈”(堆栈)。<br>“栈”是一种后进先出（先进后出），LIFO 的数据结构，也就是最新添加的最早被删除，不过在栈这种数据结构中，向栈中添加数据被称之为“入栈”(推入)，移除数据则称之为“出栈”(弹出)，因此在栈中，数据的入栈与出栈只会在一个位置进行 — 既“栈”的顶部（栈头）。</p>
<p>对“栈”的更形象理解，可以想像成一个空的容器，容器的底部是栈底，而容器的入口便是栈头，然后不断的向这个容器内部加入物件，一直塞满为止，当容器已经塞满的时候，若想再加入只能在容器的入口处将最近一次新添加的物件移出。</p>
<p><img src="/2019/04/01/professional-javascript-chapter-5-Array/stack.png" alt=""></p>
<p>ECMAScript 实现栈的行为主要借助 <code>push()</code> 、<code>pop()</code> 等方法。</p>
<ul>
<li><code>push()</code> ：向数组的尾部追加新的数组元素。返回更新后的数组长度。</li>
<li><code>pop()</code> ：删除数组尾部的最后一项，返回被删除的数组元素。</li>
</ul>
<p>通过使用 <code>pop()</code> 、<code>push()</code> 来模拟“栈”的结构。那么栈头的位置就是数组的尾部，因为这两个方法都是对数组的尾部进行操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//假设“栈”最多只能放置3个物件。</span></span><br><span class="line"><span class="keyword">var</span> number = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>); </span><br><span class="line"></span><br><span class="line">number.push(<span class="number">1</span>);</span><br><span class="line">number.push(<span class="number">2</span>);</span><br><span class="line">number.push(<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//此时重新加入第4个物件，则必须将栈顶的物件3移除。</span></span><br><span class="line">number.pop();</span><br><span class="line"></span><br><span class="line"><span class="comment">//移出后，便可以再加入物件4.</span></span><br><span class="line">number.push(<span class="number">4</span>);</span><br></pre></td></tr></table></figure>
<h2 id="队列"><a href="#队列" class="headerlink" title="队列"></a>队列</h2><p>“栈”的数据结构使其操作与访问要遵循“后进先出（LIFO）”的规则，而“队列”这种数据结构使其访问与操作要遵循 “先进先出（FIFO）”的规则，队列中的数据，从队列的末端被添加，然后在队列的前端移除。<br>形象的理解，队列（Queue）就像是现实生活中排队买东西一样，先排先处理，后来者则在队尾进行排队等待处理。</p>
<p><img src="/2019/04/01/professional-javascript-chapter-5-Array/queue.png" alt=""> </p>
<p>使用数组来模拟队列，需要借助 <code>shift()</code> 、<code>push()</code> 等方法。</p>
<ul>
<li><code>shift()</code> ：删除数组第一个元素，并返回被删除的数组元素。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//已经排好的队伍</span></span><br><span class="line"><span class="keyword">var</span> queue = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">//此时来了第四个人，则向后排队</span></span><br><span class="line">queue.push(<span class="number">4</span>);</span><br><span class="line"><span class="comment">//开始处理每次队列的第一个人</span></span><br><span class="line">queue.shift();</span><br><span class="line"></span><br><span class="line">queue.push(<span class="number">5</span>);</span><br><span class="line">queue.shift();</span><br><span class="line"></span><br><span class="line"><span class="comment">//....</span></span><br></pre></td></tr></table></figure>
<p>一般来说这种从队首移除，从队尾添加的顺序是默认的队列规则，当然也可以从队首添加，队尾删除，像这种队列则称之为 “反向队列 (reverse queue)”。</p>
<p><img src="/2019/04/01/professional-javascript-chapter-5-Array/reserve_queue.png" alt=""></p>
<p>实现反向队列则需要借助 <code>unshift()</code> 与  <code>pop()</code>。</p>
<ul>
<li><code>unshift()</code> ：向数组的首部添加元素，并返回添加后的数组长度。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> <span class="built_in">Array</span>();</span><br><span class="line"></span><br><span class="line">colors.unshift(<span class="string">"red"</span>, <span class="string">"green"</span>);</span><br><span class="line">colors.unshift(<span class="string">"black"</span>);</span><br><span class="line"></span><br><span class="line">colors.pop(); <span class="comment">//green</span></span><br></pre></td></tr></table></figure>
<h2 id="数组排序"><a href="#数组排序" class="headerlink" title="数组排序"></a>数组排序</h2><p>数组中最简单的排序方法便是 <code>reverse()</code>。<br><code>reverse()</code> 方法会对原数组进行颠倒重排，并永远改变原数组中数组元素的顺序。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"></span><br><span class="line">arr.reverse();</span><br><span class="line">arr; <span class="comment">//[3,2,1]</span></span><br></pre></td></tr></table></figure>
<p>再复杂些的排序方法便是数组的 <code>sort()</code> 方法，<code>sort()</code> 方法默认升序排序，并且会自动将数组元素转换为字符串，然后按照 ASCII 码大小进行排序。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">15</span>, <span class="number">10</span>];</span><br><span class="line"></span><br><span class="line">arr.sort();</span><br><span class="line">arr; <span class="comment">//[0,1,10,15,5];</span></span><br></pre></td></tr></table></figure>
<p>如果只是单单的将数组元素转换为字符进行大小比较，必然无法满足一些更为复杂的使用场景，因此 <code>sort()</code> 方法也接收一个回调函数，来自定义排序的行为：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compare</span>(<span class="params">value1, value2</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (value1 &lt; value2) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">if</span> (value1 &gt; value2) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">arr.sort(compare); <span class="comment">//[0,1,5,10,15];</span></span><br></pre></td></tr></table></figure>
<p><code>sort()</code> 的回调函数可以接收两个参数，如果第一个参数应在第二个参数之前，则回调函数返回一个负数，如果第一个参数在第二个参数之后，则返回一个正数，如果两个参数相等则返回 0 .</p>
<p>在上面的示例中，因为采用的是升序排序，所以会对值的大小进行判断（如果第一个值小于第二个值，既第一个值要在第二个值之前，此时返回 -1，如果第一个值大于第二个值，既第一个值实际要在第二个值之后，此时返回 1，除了以上两种情况，默认则返回0）。</p>
<p>同样的，如果打算降序排序，则只需将以上条件的返回值取反即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (value1 &lt; value2) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line"><span class="keyword">if</span> (value1 &gt; value2) <span class="keyword">return</span> <span class="number">-1</span>;</span><br></pre></td></tr></table></figure>
<p>通常情况下，如果我们能保证要进行排序的数组，其数组的元素都是数值类型，并默认升序排序，直接返回两个参数的的差值即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compare</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> value1 - value2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过传入自定义排序方法，还可以解决结构较为复杂的数据排序问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">3</span>, <span class="attr">name</span>: <span class="number">3</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">5</span>, <span class="attr">name</span>: <span class="number">5</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">id</span>: <span class="number">4</span>, <span class="attr">name</span>: <span class="number">4</span> &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>若要对这样的 JSON 数据按照 id 排序，则只需在 <code>sort()</code> 方法中进行 id 大小的比较即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">arr.sort(<span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123; <span class="keyword">return</span> a.id - b.id; &#125;);</span><br></pre></td></tr></table></figure>
<p>实际上 <code>sort</code> 方法的实现标准并没有纳入 ECMAScript 中，因此不同的浏览器，采用的算法也不相同，就以 Chrome 为例，在排序数组长度较短的时候，采用“插入排序”，当数组较为复杂的时候则采用“快速排序”算法。</p>
<p>这里简单的介绍下“插入排序”，我们可以想象现在有一个队伍（数组），队伍中人的年龄分布是无序的，现在要按照人的年龄大小来对对队伍进行排序（升序），若采用“插入排序”算法，便是从队伍的第二个人开始，让它与之前的人对比，如果前面的人年龄比自己大，则调换位置，调换位置后继续向当前位置的前一个比较，按照这个顺序继续比较下去，直到发现前一个人的年龄比自己小为止。<br>当第二个比较完毕后，接着便是队伍中的第三个数也依次进行大小比较和位置的相互交替，直到队伍的最后一个人对比完成方才结束整个轮番对比。</p>
<p>简单的说，插入排序的方式有些傻，首先不考虑队伍中的第一个人，直接从第二个人开始抓壮丁，先拉着第二个人与被忽略的第一个人比较，如果第二个大于第一个，则保持位置不变，接着再拉第三个壮丁，再依次于第二个人，第一个人比，如果第三个人的年龄小于第二个人，则两者交替位置（原本的第三变成了第二，原本的第二现在是第三）再接着从当前的位置继续向第一个比较…. 按照这样的规则每次用一个人跟队伍所有人轮番比较，直到最后一个人为止，所以“插入排序”在数据量小的情况下更简单明了，但是在数据量大的情况下，性能并非最理想。</p>
<p>下面是用 ECAMScript 来实现一个简单的 “插入排序”：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertSort</span>(<span class="params">arry</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> temp;</span><br><span class="line">    <span class="keyword">var</span> j;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//从第二个开始</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; arry.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//保存被对比的数 (每次的壮丁)</span></span><br><span class="line">        temp = arry[i];</span><br><span class="line"></span><br><span class="line">        <span class="comment">//初始化第一个要对比数的下标。</span></span><br><span class="line">        j = i - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (arry[j] &gt; temp) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//如果被对比数小于当前进行对比的数，则互换位置。</span></span><br><span class="line">            arry[j + <span class="number">1</span>] = arry[j];</span><br><span class="line"></span><br><span class="line">            <span class="comment">//继续轮询对比</span></span><br><span class="line">            j--;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/* </span></span><br><span class="line"><span class="comment">         * 循环结束，则最后一个位置的索引 +1 </span></span><br><span class="line"><span class="comment">         * 满足条件: j--，不满足条件：j=i-1，便总是当前对比数的位置 </span></span><br><span class="line"><span class="comment">         * 也就是不论有没有满足条件，总要把壮丁再放回去。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">        arry[j + <span class="number">1</span>] = temp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> arry;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面是 “插入排序的GIF” 演示：</p>
<p><img src="/2019/04/01/professional-javascript-chapter-5-Array/insert-sort.gif" alt=""></p>
<blockquote>
<p>注意的是 <code>sort()</code> 方法也会永远改变原数组中元素的排列顺序。</p>
</blockquote>
<h2 id="数组操作"><a href="#数组操作" class="headerlink" title="数组操作"></a>数组操作</h2><p>下面是 ECMAScript 提供的一些对数组进行操作处理的方法。</p>
<h3 id="合并数组"><a href="#合并数组" class="headerlink" title="合并数组"></a>合并数组</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> rgb = [<span class="number">000</span>, <span class="number">255</span>];</span><br><span class="line"><span class="keyword">var</span> hex = [<span class="string">'#000'</span>, <span class="string">'#fff'</span>];</span><br><span class="line"><span class="keyword">var</span> color = rgb.concat(hex);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(rgb); <span class="comment">//(2) [0, 255]</span></span><br><span class="line"><span class="built_in">console</span>.log(hex); <span class="comment">//(2) ["#000", "#fff"]</span></span><br><span class="line"><span class="built_in">console</span>.log(color); <span class="comment">//(4) [0, 255, "#000", "#fff"]</span></span><br></pre></td></tr></table></figure>
<p><code>concat()</code> 方法还可以同时合并多个数组。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rgb.concat(hex, hsl, ymlk);</span><br></pre></td></tr></table></figure>
<p><code>concat()</code> 只是合并数组，返回一个所有数组的合集，并不会像 <code>sort</code>，<code>reverse</code> 等方法一样会永远改变数组的结构与数据项的顺序。</p>
<h3 id="截取数组"><a href="#截取数组" class="headerlink" title="截取数组"></a>截取数组</h3><p><code>slice</code> 方法可以根据参数的起始位置与结束位置，从原数组中截取一段数组元素组成一个新的数组，并不会改变原数组对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.slice(start,end)</span><br></pre></td></tr></table></figure>
<p><code>start</code> 是截取的起始位置，<code>end</code> 则是截取的结束位置，但并不会包含 <code>end</code> 所指向的那个数据项，也就是每次截取的都是 <code>(start ~ end - 1)</code>。用区间表示：<code>[a,b)</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colorArr = [<span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>];</span><br><span class="line"></span><br><span class="line">colorArr.slice(<span class="number">1</span>, <span class="number">1</span>); <span class="comment">//[]</span></span><br><span class="line">colorArr.slice(<span class="number">1</span>, <span class="number">2</span>); <span class="comment">//["green"]</span></span><br></pre></td></tr></table></figure>
<p>如果 <code>end</code> 结束位置为空，则表示从开始位置值截取到数组的末尾。<br>如果 <code>end</code> 结束位置为负数，则用这个负数加上数组的长度，得到的结果才是 end 真正的值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">colorArr.slice(<span class="number">0</span>, <span class="number">-2</span>); <span class="comment">//["red"]</span></span><br></pre></td></tr></table></figure>
<h3 id="插入-删除-覆盖"><a href="#插入-删除-覆盖" class="headerlink" title="插入/删除/覆盖"></a>插入/删除/覆盖</h3><p>使用数组的 <code>splice</code> 方法可以对原数组进行插入/删除/覆盖操作。<br>其返回值是数组中被删除的或被覆盖的元素组成的新数组。如果进行的是插入操作那么返回的值便是一个空数组。<br>注意：splice 方法会改变原数组。<br>格式：<code>Array.splice(S[, R, item1, item2, item3, ...])</code></p>
<p><code>S</code> 指的是在原数组中进行操作的起始位置。<br><code>R</code> 表示要删除或要覆盖的元素个数。<br><code>item</code> 是要插入或覆盖（R值存在）的数组元素，数量不限。当 <code>item</code> 存在并且 <code>R</code> 为 0 ，则进行的是插入操作，当 <code>R</code> 不为 0，也存在 item 时，则进行的是覆盖操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//删除操作</span></span><br><span class="line"><span class="keyword">var</span> colors = [<span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"blue"</span>];</span><br><span class="line"><span class="keyword">var</span> A = colors.splice(<span class="number">0</span>, <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(colors); <span class="comment">//(2) ["green", "blue"]</span></span><br><span class="line"><span class="built_in">console</span>.log(A); <span class="comment">//["red"]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//插入操作</span></span><br><span class="line"><span class="keyword">var</span> B = colors.splice(<span class="number">0</span>, <span class="number">0</span>, <span class="string">"yellow"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(colors) <span class="comment">//(3) ["yellow", "green", "blue"</span></span><br><span class="line"><span class="built_in">console</span>.log(B); <span class="comment">//[]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//覆盖操作</span></span><br><span class="line"><span class="keyword">var</span> C = colors.splice(<span class="number">1</span>, <span class="number">1</span>, <span class="string">"purple"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(colors) <span class="comment">//(3) ["yellow", "purple", "blue"]</span></span><br><span class="line"><span class="built_in">console</span>.log(C); <span class="comment">//["green"]</span></span><br></pre></td></tr></table></figure>
<h2 id="位置方法"><a href="#位置方法" class="headerlink" title="位置方法"></a>位置方法</h2><p>ECMAScript5 为数组对象新增了两个位置方法：<code>indexOf()</code> 与 <code>lastIndexOf()</code>。<br>它们与 <code>String</code> 对象的方法在参数与功能上非常相同。都接收两个参数，一个是要查找的数组元素，另一个则是被查找数组中的起始位置（默认为0）。<br>它们的区别，顾名思义，一个从数组的开头向后查找(indexOf)，另一个则从数组的末尾向前查找(lastIndexOf)，它们的返回值都是一个数值型，即该元素在被查找数组中的索引位置。<br>如果没有匹配到，则返回 -1。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].indexOf(<span class="number">3</span>,<span class="number">1</span>); <span class="comment">//2</span></span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].indexOf(<span class="number">2</span>,<span class="number">2</span>); <span class="comment">//-1</span></span><br></pre></td></tr></table></figure>
<p><code>indexOf</code> 与 <code>lastIndexOf</code> 也可以查找一个引用类型的数组元素，但被查找数组中若没有相同引用的数组元素，那么必然返回 -1 。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> person = &#123; <span class="attr">name</span>: <span class="string">'zhangsan'</span> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> poople = [&#123; <span class="attr">name</span>: <span class="string">'zhangsan'</span> &#125;];</span><br><span class="line"><span class="keyword">var</span> wrapPerson = [person];</span><br><span class="line"></span><br><span class="line">poople.indexOf(person); <span class="comment">// -1;</span></span><br><span class="line">wrapPerson.indexOf(person) <span class="comment">//0</span></span><br></pre></td></tr></table></figure>
<p>另外 <code>indexOf()</code> 与 <code>lastIndexOf()</code> 的结合使用还可以巧妙的对数组进行去重。例如去除数组 A 与数组 B 中重复的元素，并用一个新的数组保存两者不重复的元素。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> A = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>];</span><br><span class="line"><span class="keyword">var</span> B = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>];</span><br><span class="line"><span class="keyword">var</span> C = A.concat(B);</span><br><span class="line"><span class="keyword">var</span> repet = [];</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; C.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (C.indexOf(C[i]) === C.lastIndexOf(C[i])) &#123;</span><br><span class="line">        repet.push(C[i]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="迭代方法"><a href="#迭代方法" class="headerlink" title="迭代方法"></a>迭代方法</h2><p>ECMAScript5 专门为数组新增了5个迭代方法：<code>some、every、filter、map、forEach</code>。<br>它们都接收两个参数：</p>
<ul>
<li>迭代处理器：迭代回调函数。</li>
<li>迭代器函数中的作用域对象：<code>this</code>。</li>
</ul>
<p>其中迭代器方法又接受三个参数，每次迭代的数据项，每次数据项的索引以及数组对象本身。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="keyword">var</span> className = &#123; <span class="attr">name</span>: <span class="string">"班"</span> &#125;;</span><br><span class="line"><span class="keyword">var</span> classes = Arr.map(<span class="function"><span class="keyword">function</span>(<span class="params">item, index, arr</span>) </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">console</span>.log(index);</span><br><span class="line">    <span class="built_in">console</span>.log(arr);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> item + <span class="keyword">this</span>.name;</span><br><span class="line">&#125;, className);</span><br></pre></td></tr></table></figure>
<p>迭代器函数中的作用域对象可以解决迭代器函数内部对上一级作用域的引用，当然如果学到了 ES6 箭头函数则会更加方便高效。</p>
<p>下面从这五个迭代方法的使用频率来逐个讲解：</p>
<p><strong>some / ervery</strong><br>关键字：迭代查询<br>返回值：Boolean。</p>
<ul>
<li>some：只要迭代器方法中返回 <code>true</code>，则 <code>some</code> 迭代的结果便为 true。除非全为 false。</li>
<li>every: 只要迭代器方法返回 false，则 every 迭代的结果便为 false，除非全为true，则结果为 true。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Arry = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="keyword">var</span> Some = Arry.some(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123; <span class="keyword">return</span> item &gt; <span class="number">2</span> &#125;);</span><br><span class="line"><span class="keyword">var</span> Every = Arry.every(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123; <span class="keyword">return</span> item &gt; <span class="number">2</span> &#125;);</span><br><span class="line"></span><br><span class="line">Some <span class="comment">// true。</span></span><br><span class="line">Every <span class="comment">// false。</span></span><br></pre></td></tr></table></figure>
<p>简单来说：<code>some()</code> 方法只要数组中有某一个元素满足特定条件，则返回 <code>true</code>。<code>every()</code> 方法只有数组中的所有元素都满足特定的条件，才会返回 <code>true</code>。</p>
<p><strong>filter</strong><br>关键字：迭代筛选<br>返回值：数组（Array）<br>功能：返回由迭代器方法返回值为 true 时的数据项组成的新数组。<br>示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Filter = Arry.filter(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123; <span class="keyword">return</span> item &gt; <span class="number">2</span> &#125;);</span><br><span class="line">Filter <span class="comment">//[3,4,5]</span></span><br></pre></td></tr></table></figure>
<p><strong>map</strong><br>关键字：迭代返回<br>功能：通过迭代器方法每次返回的数组元素组成新的数组，如果没有指定返回(<code>return</code>)值，则默认返回 <code>undefined</code>。<br>返回值：Array。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> map = Arry.map(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (item &gt; <span class="number">2</span>) <span class="keyword">return</span> item * <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">return</span> item;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">nap; <span class="comment">// [1, 2, 6, 8, 10]</span></span><br></pre></td></tr></table></figure>
<p><strong>forEach</strong><br>关键字：纯粹(pure)迭代。<br>说明：<code>forEach</code> 类似于 for 循环，单纯只为迭代数组元素，并不返回值。</p>
<p>最后，迭代方法一览表：</p>
<table>
<thead>
<tr>
<th style="text-align:center">方法名</th>
<th style="text-align:center">返回值</th>
<th style="text-align:left">应用场景</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">some</td>
<td style="text-align:center">Boolean</td>
<td style="text-align:left">遍历检索数组中元素是否满足特定的条件</td>
</tr>
<tr>
<td style="text-align:center">every</td>
<td style="text-align:center">Boolean</td>
<td style="text-align:left">遍历检索数组中元素是否满足特定的条件</td>
</tr>
<tr>
<td style="text-align:center">filter</td>
<td style="text-align:center">Array</td>
<td style="text-align:left">筛选符合条件的数组项，组成新的数组</td>
</tr>
<tr>
<td style="text-align:center">map</td>
<td style="text-align:center">Array</td>
<td style="text-align:left">通过每次遍历返回的值组成新的数组</td>
</tr>
<tr>
<td style="text-align:center">forEach</td>
<td style="text-align:center">/</td>
<td style="text-align:left">单纯遍历，无返回值</td>
</tr>
</tbody>
</table>
<h2 id="归并方法"><a href="#归并方法" class="headerlink" title="归并方法"></a>归并方法</h2><p>数组的归并方法与迭代方法相同都可以对数组进行遍历。<br>归并方法也接收一个迭代器函数，作为遍历时的处理函数，这个处理函数同时也接收四个参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Arry.reduce(prev, cur, index, array);</span><br></pre></td></tr></table></figure>
<ul>
<li>prev : 上一个值。</li>
<li>cur  : 当前值</li>
<li>index : 当前遍历的索引</li>
<li>array : 数组本身</li>
</ul>
<p>与迭代方法不同的是，归并方法的第二个参数不是用于指定回调函数的“作用域对象”，而是初始遍历的基础值（可以理解这个值才是遍历数组的第一个元素）。<br>数组的归并方法，常用于获取数组中所有项之和。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Arry = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="keyword">var</span> reduce = Arry.reduce(<span class="function"><span class="keyword">function</span>(<span class="params">prev, cur, index, array</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> prev + cur;</span><br><span class="line">&#125;, <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">reduce <span class="comment">//16</span></span><br></pre></td></tr></table></figure>
<p>如果要执行合并的数组元素是引用类型，则需要进行特定的使用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [&#123; <span class="attr">num</span>: <span class="number">1</span> &#125;, &#123; <span class="attr">num</span>: <span class="number">2</span> &#125;, &#123; <span class="attr">num</span>: <span class="number">3</span> &#125;];</span><br><span class="line">arr.reduce(<span class="function">(<span class="params">a, b, c</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> a + b.num;</span><br><span class="line">&#125;, <span class="number">0</span>);</span><br></pre></td></tr></table></figure>
<p>另外还有一个 <code>reduceRight</code> 方法，其功能与 <code>reduce</code> 相同，参数也相同，区别只是遍历的方向相反。此时作为第二个参数的初始值在 <code>reduceRight</code> 便是最后一个元素。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/01/professional-javascript-chapter-5-Object/" rel="next" title="《JavaScript 高级程序设计》第五章：Object">
                <i class="fa fa-chevron-left"></i> 《JavaScript 高级程序设计》第五章：Object
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/02/professional-javascript-chapter-5-Function/" rel="prev" title="《JavaScript 高级程序设计》第五章：Function">
                《JavaScript 高级程序设计》第五章：Function <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#legnth"><span class="nav-number">2.</span> <span class="nav-text">legnth</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#检测数组"><span class="nav-number">3.</span> <span class="nav-text">检测数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转换方法"><span class="nav-number">4.</span> <span class="nav-text">转换方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#栈方法"><span class="nav-number">5.</span> <span class="nav-text">栈方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#队列"><span class="nav-number">6.</span> <span class="nav-text">队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组排序"><span class="nav-number">7.</span> <span class="nav-text">数组排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组操作"><span class="nav-number">8.</span> <span class="nav-text">数组操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#合并数组"><span class="nav-number">8.1.</span> <span class="nav-text">合并数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#截取数组"><span class="nav-number">8.2.</span> <span class="nav-text">截取数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#插入-删除-覆盖"><span class="nav-number">8.3.</span> <span class="nav-text">插入/删除/覆盖</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#位置方法"><span class="nav-number">9.</span> <span class="nav-text">位置方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#迭代方法"><span class="nav-number">10.</span> <span class="nav-text">迭代方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#归并方法"><span class="nav-number">11.</span> <span class="nav-text">归并方法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
